package com.example.demo.controller;

import com.example.demo.utils.FileUploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/demo")
public class DemoController {

    // 创建日志记录器
    private static final Logger logger = LoggerFactory.getLogger(DemoController.class);

    // 定义文件保存的目录
    private static final String UPLOAD_DIR = "src/main/resources/uploads";


    @GetMapping("/hello")
    public String sayHello() {
        logger.debug("这是一条调试日志");
        logger.info("这是一条信息日志");
        logger.warn("这是一条警告日志");
        logger.error("这是一条错误日志");
        return "Hello, Spring Boot!";
    }

    @GetMapping("/getFile")
    public ResponseEntity<Resource> getFile() throws IOException {
        logger.info("test /getFile");
        // 从类路径下获取图片资源
        Resource resource = new ClassPathResource("static/template/1.txt");
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
//        inline会显示内容而不是自动下载，设为attachment附件
//        headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=1.txt");
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=1.txt");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .contentType(MediaType.TEXT_PLAIN)
                .body(resource);
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        FileUploadUtil fu = new FileUploadUtil();
        if (file.isEmpty()) {
            return "上传的文件为空，请选择文件后再上传。";
        }
        try {
           String filePath =  fu.uploadFile(file);
           logger.info(filePath);
            return "文件上传成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败，请稍后重试。";
        }
    }
}